package vn.buffalocoders.rikos.ui.category;
import java.util.ArrayList;


import vn.buffalocoders.rikos.R;
import vn.buffalocoders.rikos.ui.category.CategoryActivity.GetCategoryTask;
import vn.buffalocoders.rikos.ui.common.FacebookApplication;
import vn.buffalocoders.rikos.ui.common.RikoBook;
import vn.buffalocoders.rikos.ui.common.sessions.SessionManager;
import vn.buffalocoders.rikos.ui.mylibrary.MyLibraryActivity;
import vn.buffalocoders.rikos.ui.network.ConnectRikoServer;
import vn.buffalocoders.rikos.ui.network.DownloadImageTask;
import android.content.Context;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import android.widget.ViewSwitcher;

public class BookAdapter extends BaseAdapter implements OnClickListener{
	private Context context;
    private ArrayList<RikoBook> listbook;
    private View gridView;
    private SessionManager session;
	public BookAdapter(Context context, ArrayList<RikoBook> listbook) {
	    this.context = context;
	    this.listbook = listbook;
	    session = new SessionManager(context);
	}
		 
    public View getView(int position, View convertView, ViewGroup parent) {
	 
    	LayoutInflater inflater = (LayoutInflater) context
    								.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

	    if (convertView == null) {	 
	         gridView = new View(context);
 	         gridView = inflater.inflate(R.layout.book_header_view, null);
             final RikoBook book = listbook.get(position);

             //Set Image Book
             BookCover img_book = (BookCover) gridView.findViewById(R.id.img_book_cover);
             img_book.setOnClickListener(this);
             img_book.setNameBook(book.getTitle());      
             new DownloadImageTask((ImageView) img_book)
                           .execute(String.format("%s%s", ConnectRikoServer.URL_IMAGE_HOME, book.getImageCover()));
             img_book.setScaleType(ScaleType.FIT_XY);
             //Switcher book free or not
             ViewSwitcher switcher = (ViewSwitcher) gridView.findViewById(R.id.viewSwitcherPriceBook);
             switcher.setOnClickListener(this);
             //Number of like
             TextView txtLikeNum = (TextView) gridView.findViewById(R.id.txtLikeNum);
             txtLikeNum.setText(book.getLikeNum()+"");
             //Number of comment
             TextView txtCmNum = (TextView) gridView.findViewById(R.id.txtCmNum);
             txtCmNum.setText(book.getCommentNum()+"");
             //Check book free or not free
             if(book.getFee() == 1) // No free
             {
            	 View viewPriceBook = (View) gridView.findViewById(R.id.layout_pricebook);
            	 viewPriceBook.setOnClickListener(this);
            	 TextView txtPriceBuy = (TextView) gridView.findViewById(R.id.txtPriceBuy);
            	 TextView txtPriceOld = (TextView) gridView.findViewById(R.id.txtPriceOld);
            	 //Price Sale off
	        	 if(book.getPriceSale() != ""){
	        		 txtPriceBuy.setText(book.getPriceSale()+ "d");
		  	       //Price Old
	            	 if(book.getPrice() != ""){  
	            		 txtPriceOld.setText(book.getPrice() + "d"); 
	            		 txtPriceOld.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG);	            		 
	            	 }
	        	 }	 
	        	 else {
	        		 if(book.getPrice() != ""){
	        			 txtPriceBuy.setText(book.getPrice() + "d");
	            	 }
	        		 txtPriceOld.setVisibility(View.INVISIBLE); 
	        	 }
             } else // Free Book
             {
            	 switcher.showNext(); 
            	 View viewaddFreeBook = (View) gridView.findViewById(R.id.layout_add_freebook);
            	 // viewaddFreeBook.setOnClickListener(this);
            	 viewaddFreeBook.setOnClickListener( new OnClickListener() {
      			   @Override
    			   public void onClick(View v) {      				   
      				   AddBookMyLib  addbookTask = new AddBookMyLib();
      				   addbookTask.execute(book.getId(), book.getNumber().toString());      				
    			   }
    			});
             }
             // Set ranking image
             ImageView image_star5 = (ImageView) gridView .findViewById(R.id.img_star5);
             ImageView image_star4 = (ImageView) gridView .findViewById(R.id.img_star4);
             ImageView image_star3 = (ImageView) gridView .findViewById(R.id.img_star3);
             ImageView image_star2 = (ImageView) gridView .findViewById(R.id.img_star2);
             ImageView image_star1 = (ImageView) gridView .findViewById(R.id.img_star1);
             int star = book.getRanking();
             if(star < 5){
            	 image_star5.setVisibility(View.INVISIBLE);
             if(star < 4 ){
            	 image_star4.setVisibility(View.INVISIBLE);
             if(star < 3){
                 image_star3.setVisibility(View.INVISIBLE);
             if(star < 3) {
                 image_star3.setVisibility(View.INVISIBLE);
             if(star < 2){
                 image_star2.setVisibility(View.INVISIBLE);
             if(star < 1){
                 image_star1.setVisibility(View.INVISIBLE);}}}}}}
            	 
             //Book mark
             if(book.getPageBookMark() == 0)
             {
            	 ImageView bookmark = (ImageView) gridView .findViewById(R.id.bookmark);
            	 bookmark.setVisibility(View.INVISIBLE);
             }
         
             View viewLayoutLoveComment = (View) gridView.findViewById(R.id.layoutlovecomment);
             viewLayoutLoveComment.setOnClickListener(this);

             
	    }
	    else{
	       	gridView = (View) convertView;
	    }
	    return gridView;
	   }
	 
 	@Override
    public int getCount() {
 		 return listbook.size();
 	 }
 	 
    @Override
    public Object getItem(int position) {
         return null;
	}
 	 
    @Override
    public long getItemId(int position) {
    	
        return position;
    }

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
		if(v.getId() == R.id.img_book_cover) {
			BookCover view = (BookCover) v;
			// Toast.makeText(context,  "Book name " + view.getNameBook(), Toast.LENGTH_LONG).show();
		   //	Toast.makeText(context,  "IMAGE", Toast.LENGTH_LONG).show();
	    	// Intent intent = new Intent(context, SignUpActivity.class);
	    	// startActivity(intent);
			return ;
		}
		
		if(v.getId() == R.id.layoutlovecomment){
			// Toast.makeText(context,  "LOve", Toast.LENGTH_LONG).show();
			return;
		}

		if(v.getId() == R.id.layout_add_freebook){
			// Toast.makeText(context,  "Add book to my list book", Toast.LENGTH_LONG).show();
			return;
		}

		if(v.getId() == R.id.layout_pricebook){
			// Toast.makeText(context,  "Show detail book", Toast.LENGTH_LONG).show();
			return;
		}
			
	} 

	public class AddBookMyLib extends AsyncTask<Object /* param */, Void /* Progress */, Integer /* Result */> {

		@Override
		protected Integer  doInBackground(Object... param) {
			// TODO Auto-generated method stub			
			Log.i("DBT_TEST", String.format("AddBookMyLibTask authToken=%s,userID=%s, bookid=%s, number=%s ", 
					session.getAuthToken(), session.getUserId(),  (String)param[0], (String)param[1]));				
			return ConnectRikoServer.addBookToMyLibrary(session.getAuthToken(), session.getUserId(), 
					(String)param[0], (String)param[1]);

		}

		@Override
		protected void onPostExecute(Integer result) {
			if(result == 1) {
				// Toast.makeText(context,  "Add Book Success", Toast.LENGTH_LONG).show();
			}
			else {
				// Toast.makeText(context,  "Add Book Failed " , Toast.LENGTH_LONG).show();
			}
		}

		@Override
		protected void onCancelled() {
			
		}
		
	}
}
